/*

*/

#include "singlelist.h"



node* head = NULL;
int nd_count = 0;

node* sl_create_node(int num){
    node* nd = (node*) malloc(sizeof(node));
    nd->num = num;
    nd->next = NULL;
    return nd;
}

//打印链表
void sl_print(){
    if(NULL == head){
        printf("sl is empty \n");
        return;
    }
    node* nd = head;
    while(nd != NULL){
        printf("%d ", nd->num);
        nd = nd->next;
    }
    printf("\nsl_print end \n\n");
}

node* sl_gethead(){
    return head;
}

//增加节点
void sl_add(node* nd){
    node* tmp = head;
    if(head == NULL){
        head = nd;
        return;
    }
    while(tmp->next != NULL){
        tmp = tmp->next;
    }
    tmp->next = nd;
}

void sl_del(node* nd){
    node* cur_node = head;
    node* pre_node = NULL;
    while(cur_node){
        if(cur_node->num == nd->num){
            if(pre_node){
                pre_node->next = cur_node->next;
            }else{
                head = head->next;
            }
            free(cur_node);
            cur_node = NULL;
            break;
        }
        pre_node = cur_node;
        cur_node = cur_node->next;
    }
}



int lua_sl_add(lua_State* L){
    /*  读取lua中传入一个table数组
        把数组的值转为 node
        加入到链表中
    */
    luaL_checktype(L, -1, LUA_TTABLE);
    int len = luaL_len(L, -1); //table数组长度
    for(int i = 1; i <= len; i++){
        lua_pushinteger(L, i);
        lua_gettable(L, -2); //把t[k]的值弹出到栈顶
        int num = luaL_checkinteger(L, -1); //取出栈顶value
        lua_pop(L, 1); //弹出栈顶元素
        node* nd = sl_create_node(num);
        sl_add(nd);
    }
//    sl_print();

    lua_newtable(L);
    node* tmp = head;
    int k = 1;
    while(tmp){
        lua_pushinteger(L, k++);
        lua_pushinteger(L, tmp->num);
        lua_settable(L, -3);
        tmp = tmp->next;
    }

    return 1;

}

int lua_sl_del(lua_State* L){
    luaL_checktype(L, -1, LUA_TNUMBER);
    int num = luaL_checkinteger(L, -1);
    node* nd = sl_create_node(num);
    sl_del(nd);
//    sl_print();
    lua_newtable(L);
    node* tmp = head;
    int k = 1;
    while(tmp){
        lua_pushinteger(L, k++);
        lua_pushinteger(L, tmp->num);
        lua_settable(L, -3);
        tmp = tmp->next;
    }

    return 1;
}